/*
    Project:        Home Power Control
    File:           HPCRainGauge.cpp
    Author:         christian@karunamusic.at
    Date:           02.2015
    Description:    Sensor to measure the amount of rain in l/m2.
                    The sensor gives one tick per 0,2794mm water in the sensor.
                    1mm is aequivalent to 1 l/m2.
 */

#include <QMutex>
#include <wiringPi.h>
#include <unistd.h>
#include <Logger/HPCLogger.h>
#include "HPCRainGauge.h"

unsigned int HPCRainGauge::m_Counter = 0;
QMutex HPCRainGauge::m_Mutex;

HPCRainGauge::HPCRainGauge(const QString& name, quint32 id, quint8 pin, quint16 interval )
    : HPCSensor( TSensorType::HPCRainGauge, name, id, pin ), m_Interval(interval), m_Timer(0)
{
    digitalWrite( m_Pin, HIGH );
    wiringPiISR( m_Pin, INT_EDGE_FALLING, &isr );

    m_Timer = new QTimer(this);
    connect( m_Timer,SIGNAL(timeout()), this, SLOT(calcAverage()) );
    m_Timer->start(m_Interval*1000);
}

HPCRainGauge::~HPCRainGauge()
{
    m_Timer->stop();
    delete m_Timer;
}

QString HPCRainGauge::asString() const
{
    QString ret = HPCSensor::asString();

    ret += ", interval " + QString::number(m_Interval);
    return ret;
}

void HPCRainGauge::isr()
{
    m_Mutex.lock();
    m_Counter++;
    m_Mutex.unlock();
}

void HPCRainGauge::Measure()
{
    // do nothing - this sensor is using the timer to calculate its value!
    LOG( trace, Name() << ": measured value: " << m_Value.V().toFloat() );
}

void HPCRainGauge::calcAverage()
{
    HPCValue res;

    // 1 tick = 0,2794mm water
    float v = ((m_Counter * 27.94) / 10.0) / m_Interval;
    float scale = 0.1;
    res.V() = floor(v / scale + 0.5) * scale;

    m_Mutex.lock();
    m_Counter = 0;
    m_Mutex.unlock();

    m_Value = res;
}
